$.post(server_url + "rest/tokenValidate/getSignature.do", {
	"url" : window.location.href.split('#')[0]
}, function(result) {
	token = 
	wx.config({
		debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		appId : appId, // 必填，公众号的唯一标识
		timestamp : result.timestamp, // 必填，生成签名的时间戳
		nonceStr : result.noncestr, // 必填，生成签名的随机串
		signature : result.signature, // 必填，签名，见附录1
		jsApiList : [ 'checkJsApi', 'chooseImage',  'previewImage', 'uploadImage','downloadImage']
	// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
	});

});
wx.ready(function() {
	wx.checkJsApi({
		jsApiList : [ 'chooseImage', 'previewImage', 'uploadImage','downloadImage'],
		success : function(res) {
			if (res.checkResult.getLocation == false) {
				alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
				return;
			}
		}
	});
});

var form;
var param = JSON.parse(localStorage.getItem('param'));
var supplyId ;
var yyzzPic = '';//营业执照
var sfzmPic = '';//身份证正面
var sffmPic = '';//身份证反面
var coverPic = '';//封面照
var jtPic = '';//交通清晰照片
var syPic = '';//水源清晰照片
var cslmPic = '';//茶树林木照片
var localIds = [];
var str = '';
if(param){
	supplyId = param.supplyId;
}
$(function(){
	layui.use(['layer', 'form'], function() {
		form = layui.form();
		init();
		initButton();
	});
});
//初始化页面
function init(){
	/*var gandenTypes = $("input[name='gandenType']");
	gandenTypes.removeProp('checked');
	var s = '1';
	console.log($(gandenTypes[1]));
	$(gandenTypes[s]).prop("checked",true);
	console.log($(gandenTypes[1]));
	form.render('radio');*/
	/*var teaTypes = $("input[name='teaType']");
	teaTypes.removeProp('checked');
	var s = '1,2'
	var ss = s.split(",");
	$.each(ss,function(i,n){
		$(teaTypes[n]).prop("checked",true);
	});
	form.render('checkbox');*/
	if(supplyId){
		//回显
		$.ajax({
			type : "get",
			url : server_url
					+ 'rest/tea/product/getTeaProductInfo.do?ran=' + Math.random(),
			dataType : 'json',
			async : true,
			data : {
				token : token,
				productId:supplyId
			},
			success : function(result) {
				console.log(result);
				if (result.retCode == '0000') {
					var product = result.data;
					$('#title').val(product.teaTitle);
					$('#legalName').val(product.legalName);
					$('#teaPhone').val(product.teaPhone);
					$('#teaArea').val(product.teaArea);
					$('#teaHight').val(product.teaHight);
					$('#coverArea').val(product.coverArea);
					$('#detailAddress').val(product.detailAddress);
					$('#limitTime').val(product.limitTime);
					$('#teaPrice').val(product.teaPrice);
					
					var gandenTypes = $("input[name='gandenType']");
					gandenTypes.removeProp('checked');
					$(gandenTypes[product.gandenType]).prop("checked",true);
					form.render('radio');
					
					var rentTypes = $("input[name='rentType']");
					rentTypes.removeProp('checked');
					$(rentTypes[product.rentType]).prop("checked",true);
					form.render('radio');
					
					$('#treeNum').val(product.treeNum);
					
					var teaTypes = $("input[name='teaType']");
					teaTypes.removeProp('checked');
					var ss = product.teaType.split(",");
					$.each(ss,function(i,n){
						$(teaTypes[n]).prop("checked",true);
					});
					form.render('checkbox');
					
					$('#teaType').val(product.teaType);
					
					$('#teaNotice').val(product.teaNotice);
					
					var pic = product.productPic;
					$('#yyzzPic').html('<img src="'+pic.yyzzPic+'" alt="" class="photo1" />');
					$('#sfzmPic').html('<img src="'+pic.sfzmPic+'" alt="">');
					$('#sffmPic').html('<img src="'+pic.sffmPic+'" alt="">');
					$('#coverPic').html(getPicPath(pic.coverPic));
					$('#jtPic').html(getPicPath(pic.jtPic));
					$('#syPic').html(getPicPath(pic.syPic));
					$('#cslmPic').html(getPicPath(pic.cslmPic));
				}else{
					showErrorMsg(result.data);
				}
			}
		});
	}
}
//初始化绑定事件
function initButton(){
	$('.pop-btn').on('click',function(){
		window.location = server_url + "thatTea.do";
	});
	//绑定法人照
	$('.add-btn').on('click',function(){
		//alert("hehe");
		wx.chooseImage({
		    count: 1, // 默认9
		    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		    success: function (res) {
		        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		        var str = "";
		        yyzzPic = "";
		        $.each(localIds,function(i,n){
		        	str += '<img src="'+n+'" alt="" style="height:124px;" class="photo1">';
		        	 wx.uploadImage({  
		                 localId: n, // 需要上传的图片的本地ID，由chooseImage接口获得  
		                 isShowProgressTips: 1, // 默认为1，显示进度提示  
		                 success: function (res) {  
		                     var mediaId = res.serverId; // 返回图片的服务器端ID
		                     $.ajax({
		                 		type : "get",
		                 		url : server_url
		                 				+ 'rest/tea/base/uploadImage.do?ran=' + Math.random(),
		                 		dataType : 'json',
		                 		async : true,
		                 		data : {
		                 			token : token,
		                 			mediaId:mediaId,
		                 			component:"yyzzPic"
		                 		},
		                 		success : function(result) {
		                 			if (result.retCode == '0000') {
		                 				yyzzPic = yyzzPic+result.data+",";
		                 				//$(".comment-con").html(imgs);
		                 			} 
		                 		}
		                 	});
		                 } 
		             });  
		        });
		        $("#yyzzPic").html(str);
		    }
		});
	});
	//绑定其他照片
	$('.add-btn3').on('click',function(){
		var type = $(this).attr('type');
		var count = 1;
		if(type=='sfzmPic'||type=='sffmPic'){
			count = 1;
	    	}else if(type=='coverPic'){
	    		count = 3;
	    	}else{
	    		count = 9;
	    	}
		wx.chooseImage({
		    count: count, // 默认9
		    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		    success: function (res) {
		    		localIds = res.localIds;
		    		str = '';
		    		if(type=='sfzmPic'){
			        	sfzmPic = "";
			    }else if(type=='sffmPic'){
			        	sffmPic = "";
			    }else if(type=='coverPic'){
			        	coverPic = "";
			    }else if(type=='jtPic'){
			        	jtPic = "";
			    }else if(type=='syPic'){
			        	syPic = "";
			    }else if(type=='cslmPic'){
			        	cslmPic = "";
			    }
	            syncUpload(type);
		    }
		});
		
		
//		wx.chooseImage({
//		    count: count, // 默认9
//		    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
//		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
//		    success: function (res) {
//		        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
//		        var str = "";
//		        if(type=='sfzmPic'){
//		        	sfzmPic = "";
//		        }else if(type=='sffmPic'){
//		        	sffmPic = "";
//		        }else if(type=='coverPic'){
//		        	coverPic = "";
//		        }else if(type=='jtPic'){
//		        	jtPic = "";
//		        }else if(type=='syPic'){
//		        	syPic = "";
//		        }else if(type=='cslmPic'){
//		        	cslmPic = "";
//		        }
//		        $.each(localIds,function(i,n){
//		        	if(type=='sfzmPic'||type=='sffmPic'){
//		        		str += '<img src="'+n+'" alt="">';
//		        	}else{
//		        		str +='<div class="img-box fl" ><img src="'+n+'" alt=""></div>';
//		        	}
//		        	 wx.uploadImage({  
//		                 localId: n, // 需要上传的图片的本地ID，由chooseImage接口获得  
//		                 isShowProgressTips: 1, // 默认为1，显示进度提示  
//		                 success: function (res) {  
//		                     var mediaId = res.serverId; // 返回图片的服务器端ID
//		                     $.ajax({
//		                 		type : "get",
//		                 		url : server_url
//		                 				+ 'rest/tea/base/uploadImage.do?ran=' + Math.random(),
//		                 		dataType : 'json',
//		                 		async : true,
//		                 		data : {
//		                 			token : token,
//		                 			mediaId:mediaId,
//		                 			component:type
//		                 		},
//		                 		success : function(result) {
//		                 			if (result.retCode == '0000') {
//		                 				if(type=='sfzmPic'){
//		                		        	sfzmPic = sfzmPic+result.data+",";
//		                		        }else if(type=='sffmPic'){
//		                		        	sffmPic = sffmPic+result.data+",";
//		                		        }else if(type=='coverPic'){
//		                		        	coverPic = coverPic+result.data+",";
//		                		        }else if(type=='jtPic'){
//		                		        	jtPic = jtPic+result.data+",";
//		                		        }else if(type=='syPic'){
//		                		        	syPic = syPic+result.data+",";
//		                		        }else if(type=='cslmPic'){
//		                		        	cslmPic = cslmPic+result.data+",";
//		                		        }
//		                 			} 
//		                 		}
//		                 	});
//		                 } 
//		             });  
//		        });
//		        $("#"+type).html(str);
//		    }
//		});
	});
	//绑定发布
	$('.address-btn-box').on('click',function(){ 
		var title = $('#title').val();
		var legalName = $('#legalName').val();
		var teaPhone = $('#teaPhone').val();
		var teaArea = $('#teaArea').val();
		var teaHight = $('#teaHight').val();
		var coverArea = $('#coverArea').val();
		var detailAddress = $('#detailAddress').val();
		var limitTime = $('#limitTime').val();
		var teaPrice = $('#teaPrice').val();
		var treeNum = $('#treeNum').val();
		var teaNotice = $('#teaNotice').val();
		
		var gandenType = $('input:radio[name="gandenType"]:checked').val();
		
		var rentType = $('input:radio[name="rentType"]:checked').val();
		
		var $teaType = $('input:checkbox:checked');
		
		var teaType = '';
		
		$.each($teaType,function(i,n){
			teaType += $(this).val()+",";
		});
		
		if(teaType.length>1){
			teaType = teaType.substring(0,teaType.length-1)
		}
		
		if(!checkNull(title,"请输入标题")){
			return;
		}
		if(!checkNull(legalName,"请输入林权所有者")){
			return;
		}
		if(!checkNull(teaPhone,"请输入联系电话")){
			return;
		}
		if(!checkNull(teaArea,"请输入转租林地面积")){
			return;
		}
		if(!checkNull(teaHight,"请输入海拔高度")){
			return;
		}
		if(!checkNull(coverArea,"请输入建房用地面积")){
			return;
		}
		if(!checkNull(detailAddress,"请输入详细地址")){
			return;
		}
		if(!checkNull(limitTime,"请输入有效期")){
			return;
		}
		if(!checkNull(teaPrice,"请输入林地价格")){
			return;
		}
		if(!checkNull(treeNum,"请输入茶树数目")){
			return;
		}
		if(!checkNull(teaNotice,"请输入设施说明")){
			return;
		}
		if(!checkNull(teaType,"请选择可制作成品茶种类")){
			return;
		}
		if(!checkNull(yyzzPic,"请上传营业执照照片")){
			return;
		}
		if(!checkNull(sfzmPic,"请上传身份证正面照")){
			return;
		}
		if(!checkNull(sffmPic,"请上传身份证反面照")){
			return;
		}
		if(!checkNull(coverPic,"请上传封面照")){
			return;
		}
		if(!checkNull(jtPic,"请上传场交通清晰照")){
			return;
		}
		if(!checkNull(syPic,"请上传水源清晰照")){
			return;
		}
		if(!checkNull(cslmPic,"请上传茶树林木照")){
			return;
		}
		
		$.ajax({
			type : "post",
			url : server_url
					+ 'rest/tea/supply/supply3.do?ran=' + Math.random(),
			dataType : 'json',
			async : true,
			data : {
				token : token,
				title:title,
				legalName:legalName,
				teaPhone:teaPhone,
				teaArea:teaArea,
				teaHight:teaHight,
				coverArea:coverArea,
				detailAddress:detailAddress,
				limitTime:limitTime,
				teaPrice:teaPrice,
				treeNum:treeNum,
				teaNotice:teaNotice,
				gandenType:gandenType,
				rentType:rentType,
				teaType:teaType,
				yyzzPic:yyzzPic.substring(0,yyzzPic.length-1),
				sfzmPic:sfzmPic.substring(0,sfzmPic.length-1),
				sffmPic:sffmPic.substring(0,sffmPic.length-1),
				coverPic:coverPic.substring(0,coverPic.length-1),
				jtPic:jtPic.substring(0,jtPic.length-1),
				syPic:syPic.substring(0,syPic.length-1),
				cslmPic:cslmPic.substring(0,cslmPic.length-1),
				supplyId:supplyId,
				lat:localStorage.getItem("lat"),
				lon:localStorage.getItem("lon"),
				userId:localStorage.getItem("userid")
			},
			success : function(result) {
				console.log(result);
				if (result.retCode == '0000') {
					jumpToIndex("发布成功",2000);
				}else{
					showErrorMsg(result.data);
				}
			}
		});
		
		
	});
}
//拼接回显的图片
function getPicPath(pics){
	var paths = pics.split(",");
	var str='';
	$.each(paths,function(i,n){
		str += '<div class="img-box fl" ><img src="'+n+'" alt=""></div>';
	});
	return str;
}
//多图上传
function syncUpload(type){
	if (!localIds.length) {
        //alert('上传成功!');
        $("#"+type).html(str);
    } else {
        var localId = localIds.pop();
	    	if(type=='sfzmPic'||type=='sffmPic'){
	    		str += '<img src="'+localId+'" alt="">';
	    	}else{
	    		str += '<div class="img-box fl" ><img src="'+localId+'" alt=""></div>';
	    	}
        wx.uploadImage({
            localId: localId,
            success: function(res) {
                var mediaId = res.serverId; // 返回图片的服务器端ID
                $.ajax({
            		type : "get",
            		url : server_url
            				+ 'rest/tea/base/uploadImage.do?ran=' + Math.random(),
            		dataType : 'json',
            		async : true,
            		data : {
            			token : token,
            			mediaId:mediaId,
            			component:type
            		},
            		success : function(result) {
        				if (result.retCode == '0000') {
             			if(type=='sfzmPic'){
             				sfzmPic = sfzmPic+result.data+",";
            		        }else if(type=='sffmPic'){
            		        		sffmPic = sffmPic+result.data+",";
            		        }else if(type=='coverPic'){
            		        		coverPic = coverPic+result.data+",";
            		        }else if(type=='jtPic'){
            		        		jtPic = jtPic+result.data+",";
            		        }else if(type=='syPic'){
            		        		syPic = syPic+result.data+",";
            		        }else if(type=='cslmPic'){
            		        		cslmPic = cslmPic+result.data+",";
            		        }
            			} else{
            				showErrorMsg(result.data);
            			}
            		}
            		});
                syncUpload(type);
            }
        });
    }
}